﻿//Thomas Arvidsson 761027-5617 @ Örebro/Sweden 2011/2012

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text;
using System.Collections.ObjectModel;
using Microsoft.Devices;



namespace PasswordGenerator
{
    public partial class MainPage : PhoneApplicationPage
    {
        private int _numberOfChars = 6;
        private bool isStrong = true;
        private string collectionWithoutSpChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        private string collectionStrong = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!%?&";

        private List<string> collPswords = new List<string>();
        public List<string> CollPasswords { get { return collPswords; } }

        private bool generatedPassword = false;
        

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            slider1.Minimum = 6;
            slider1.Value = 7;
            
        }        

        private void PrintPasswordsInListbox()
        {            
            int count = lstBoxResults.Items.Count;
            if (lstBoxResults.Items.Count > 0)
            {
                lstBoxResults.Items.Clear();
            }

            if (collPswords.Count > 0)
            {
                for (int i = collPswords.Count - 1; i >= 0; i--)
                {
                    lstBoxResults.Items.Add(collPswords[i]);
                                       
                }
            }
        }

        private void btnGenerate_Tap(object sender, GestureEventArgs e)
        {
            try
            {
                VibrateController.Default.Start(new TimeSpan(0, 0, 0, 0, 100));
                txtBlPassword.Text = "Last generated:\n" + GeneratePassword(isStrong);
                PrintPasswordsInListbox();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unknown error, please try and restart app\n" + ex.Message);
            }
        }

        private void chBoxStrongPassword_Tap(object sender, GestureEventArgs e)
        {
            SetIfStrong();
        }

        private void SetIfStrong()
        {
            if (chBoxStrongPassword.IsChecked == true)
                isStrong = true;
            if (chBoxStrongPassword.IsChecked == false)
                isStrong = false;           
        }

        /// <summary>
        /// Returns a string with generated password using a stringbuilder. 
        /// </summary>
        /// <param name="isStrong"></param>
        /// <returns></returns>
        private string GeneratePassword(bool isStrong)
        {
            StringBuilder sb = new StringBuilder(_numberOfChars);
            Random randomizer = new Random();
            int posMustHaveSpecialChar = 0;                 

            string chars;
            if (isStrong)
            {
                chars = collectionStrong;
                posMustHaveSpecialChar = randomizer.Next(0, _numberOfChars - 1);
            }
            else
            {
                chars = collectionWithoutSpChars;
            }            

            for (int i = 0; i < _numberOfChars; i++)
            {
                if (isStrong && i == posMustHaveSpecialChar)
                {
                    sb.Append(chars[randomizer.Next(chars.Length - 4, chars.Length)]);
                }
                else
                {
                    sb.Append(chars[randomizer.Next(0, chars.Length)]);
                }
            }

            var a = App.Current as App;
            a.PassWord = sb.ToString();

            collPswords.Add(sb.ToString());
            lstBoxResults.Items.Add(sb.ToString());

            if (!generatedPassword) { generatedPassword = true; }

            return sb.ToString();
        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            _numberOfChars = (int)Math.Round((double)slider1.Value, 0);
            txtBlockNrChars.Text = _numberOfChars.ToString();
        }
        
        private void btnMail_Tap(object sender, GestureEventArgs e)
        {
            if (generatedPassword)
                NavigationService.Navigate(new Uri("/MailPage.xaml", UriKind.RelativeOrAbsolute));
            else
                MessageBox.Show("Please generate a password");
        }

        private void lstBoxResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstBoxResults.Items.Count > 0)
            {
                string psswd = lstBoxResults.SelectedItem.ToString();
                txtBlPassword.Text = psswd;
                var a = App.Current as App;
                a.PassWord = psswd.ToString();
            }
            else { }//Do nothing            
        }
    }
}